#include "log.h"


#include <stdio.h>
#include <time.h>

#include <stdio.h>
#include <time.h>
#include <stdarg.h>

// 初始化日志文件，返回文件指针
void log_init(const char *filename, FILE *fp)
{
    fp = fopen(filename, "w");
    if (fp == NULL)
    {
        MakeErrorLogFile(LOG_ERROR, "%s文件初始化失败！\n文件:%s 函数:%s 行:%d ",\
                        filename, __FILE__, __FUNCTION__, __LINE__);
        perror("无法初始化日志文件");
    }
    return fp;
}

// 创建每日日志文件并写入消息
void MakeDayLogFile( const char *message, ...)
{
    time_t now = time(NULL);
    struct tm *local = localtime(&now);
    char LogName[100];
    sprintf(LogName, "DayLog_%d%02d%02d.log", local->tm_year + 1900, local->tm_mon + 1, local->tm_mday);
    char timestamp[26];
    FILE *fp = fopen(LogName, "a");
    if (fp == NULL)
    {
        
        log_init(LogName,fp );
        if (fp == NULL)
        {
            MakeErrorLogFile(LOG_ERROR, "%s文件打开失败！,已重新创建新文件！但是日志文件打开依然失败\n文件:%s 函数:%s 行:%d ",\
                        LogName, __FILE__, __FUNCTION__, __LINE__);
            return;
        }
        MakeErrorLogFile(LOG_ERROR, "%s文件打开失败！,已重新创建新文件！\n文件:%s 函数:%s 行:%d ",\
                        LogName, __FILE__, __FUNCTION__, __LINE__);
    }

    va_list args;
    va_start(args, message);
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", localtime(&now)); 
    fprintf(fp, "%s\n", timestamp);
    vfprintf(fp, message, args);
    va_end(args);

    fclose(fp);
}

// 读取指定日期的日志文件
void ReadDayLogFile(void)
{
    printf("请输入你要查看的日志文件时间(格式: 年-月-日 ):\n");
    int LogName[3];
    if (scanf("%d-%d-%d", &LogName[0], &LogName[1], &LogName[2]) != 3)
    {
        printf("输入格式错误！\n");
        return;
    }
    char LogFile[100];
    sprintf(LogFile, "DayLog_%d%02d%02d.log", LogName[0], LogName[1], LogName[2]);
    FILE *fp = fopen(LogFile, "r");
    if (fp == NULL)
    {
        MakeErrorLogFile(LOG_INFO, "%s文件打开失败！\n文件:%s 函数:%s 行:%d ",LogFile, __FILE__, __FUNCTION__, __LINE__);
        printf("日志文件不存在！\n");
        return;
    }
    char message[100];
    while (fgets(message, sizeof(message), fp) != NULL)
    {
        printf("%s", message);
    }
    fclose(fp);
}
void MakeErrorLogFile(LogLevel level,const char *message, ...)
{
    time_t now = time(NULL);
    struct tm *local = localtime(&now);
    char LogName[100];
    FILE *fp = fopen("ErrorLo.log", "a");
    char timestamp[26];
    if (fp == NULL)
    {
        log_init(LogName,fp);
        if (fp == NULL)
        {
            MakeErrorLogFile(LOG_ERROR, "ErrorLo.log文件打开失败！,已重新创建新文件！但是日志文件打开依然失败！\n文件:%s 函数:%s 行:%d", __FILE__, __FUNCTION__, __LINE__);
                return;
        }
        MakeErrorLogFile(LOG_INFO, "ErrorLo.log文件打开失败！,已重新创建新文件！\n文件:%s 函数:%s 行:%d ", __FILE__, __FUNCTION__, __LINE__);
    }

    va_list args;
    va_start(args, message);
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", localtime(&now)); 
    fprintf(fp, "%s:%d\n", timestamp, level);
    vfprintf(fp, message, args);
    va_end(args);
}
